package com.syqc.monitor.ui.singlemap

import androidx.lifecycle.MutableLiveData
import autodispose2.autoDispose
import com.amap.api.maps.AMap
import com.syqc.comlib.AppConfigs
import com.syqc.comlib.auto.AutoDisposeViewModel
import com.syqc.comlib.utils.CacheMMKV
import com.syqc.comlib.utils.GsonUtil
import com.syqc.entity.Driver
import com.syqc.entity.GpsDetail
import com.syqc.entity.VideosPass
import com.syqc.maps.utils.MarkerSet
import com.syqc.monitor.R
import com.syqc.net.ServiceHelper
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers
import io.reactivex.rxjava3.core.Flowable
import io.reactivex.rxjava3.disposables.Disposable
import io.reactivex.rxjava3.subjects.PublishSubject
import java.util.concurrent.TimeUnit

/** @Author Jasper @Time 2020/12/4 @Desc 单车监控 */
class SingleMapViewModel : AutoDisposeViewModel() {
    var gpsDetail: GpsDetail? = null
    private var subscribe: Disposable? = null

    var isCarTraffic: Boolean
        get() = CacheMMKV.decodeBoolean("single_isTraffic", true)
        set(value) = CacheMMKV.encode("single_isTraffic", value)

    //是否是车牌展示
    var isPlate: Boolean = MarkerSet.localSet.showPlate

    var mMapType: Int
        get() = CacheMMKV.decodeInt("single_isMapNormal", AMap.MAP_TYPE_NORMAL)
        set(value) = CacheMMKV.encode("single_isMapNormal", value)

    val locationSub: PublishSubject<GpsDetail> = PublishSubject.create()
    var carId: String? = null
    val startLive = MutableLiveData<Boolean>()

    //刷新时间
    private var refreshTime = AppConfigs.mapRefresh
    fun setRefreshTime(refreshTime: Int) {
        this.refreshTime = refreshTime
        AppConfigs.mapRefresh = refreshTime
        CacheMMKV.encode("refresh_time", refreshTime)
    }

    /** 获取定位信息 */
    private fun getLocation() {
        if (carId.isNullOrEmpty()) {
            toast(R.string.hint_toast_choose_car)
        } else {
            ServiceHelper.getRepository().getGpsRInfo("", carId!!)
                .autoDispose(this)
                .subscribe({
                    if (it.isNullOrEmpty()) {
                        toast(R.string.toast_no_location_other)
                        startLive.postValue(true)
                        subscribe?.dispose()
                        driverInfo.clear()
                    } else {
                        gpsDetail = it[0]
                        handlePhone(gpsDetail!!)
                        locationSub.onNext(gpsDetail!!)
                    }
                    toastLoading(false)
                }, error)
        }
    }

    /** 获取定位信息 */
    private fun getLocation2() {
        if (carId.isNullOrEmpty()) {
            toast(R.string.hint_toast_choose_car)
        } else {
            ServiceHelper.getRepository().getGpsRInfo("", carId!!)
                .autoDispose(this)
                .subscribe({
                    if (it.isNullOrEmpty()) {
                        toast(R.string.toast_no_location_other)
                        startLive.postValue(true)
                        subscribe?.dispose()
                        driverInfo.clear()
                    } else {
                        toast(R.string.toast_refresh_success)
                        gpsDetail = it[0]
                        handlePhone(gpsDetail!!)
                        locationSub.onNext(gpsDetail!!)
                    }
                    toastLoading(false)
                }, error)
        }
    }

    //司机数据
    val driverInfo = mutableListOf<Driver>()
    private fun handlePhone(carInfo: GpsDetail) {
        driverInfo.clear()
        val drvPhone = carInfo.drvPhone
        if (drvPhone.isNotEmpty() && carInfo.drvName.isNotEmpty()) {
            driverInfo.clear()
            val phones = drvPhone.split(",")
            val names = carInfo.drvName.split(",")
            for (i in phones.indices) {
                driverInfo.add(Driver(names[i], phones[i]))
            }
        }
        talkChannel = getAudioChannel(carInfo)
    }

    /** 开始请求 */
    fun startTime() {
        toastLoading(true)
        nowTime = refreshTime
        getLocation()
        timeSub.onNext(nowTime)
        subscribe?.dispose()
        subscribe =
            Flowable.interval(0, 1, TimeUnit.SECONDS)
                .observeOn(AndroidSchedulers.mainThread())
                .autoDispose(this)
                .subscribe {
                    if (nowTime == 1) {
                        nowTime = refreshTime
                    } else {
                        nowTime--
                    }
                    timeSub.onNext(nowTime)
                    if (nowTime == 1) {
                        getLocation()
                    }

                }

    }

    private var nowTime = 5
    private val timeSub by lazy { PublishSubject.create<Int>() }
    fun timeObserver() = timeSub.hide()

    fun refresh() {
        getLocation()
    }

    fun refresh2() {
        getLocation2()
    }

    /** 停止请求 */
    fun stopTime() {
        subscribe?.dispose()
    }

    fun saveRefreshTime(refreshTime: Int) {
        this.refreshTime = refreshTime
        CacheMMKV.encode("single_map_time", refreshTime)
    }

    ///////////////////////////////////////////////////////////////////////////////////////
    //对讲通道号
    var talkChannel = ""

    /**
     * 获取对讲通道号
     *
     * @return
     */
    private fun getAudioChannel(gpsDetail: GpsDetail?): String {
        if (gpsDetail?.videos == null) return ""
        var talkChannel = ""
        gpsDetail.run {
            val entity = GsonUtil.formObject<VideosPass>(videos)
            val channel = entity.tc
            talkChannel = if (channel.isNullOrEmpty()) {
                val passEntitys = entity.vs?.split(",")
                if (passEntitys.isNullOrEmpty()) {
                    ""
                } else {
                    val passInfos = passEntitys[0].split(":");
                    passInfos[0]
                }
            } else {
                channel
            }
        }
        return talkChannel
    }
}
